package com.example.shiwu.util;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

public class CmdMessenger {
    private Map<String, Consumer<String[]>> commandHandlers;
    private String delimiter;

    public CmdMessenger(String delimiter) {
        this.commandHandlers = new HashMap<>();
        this.delimiter = delimiter;
    }

    public void registerHandler(String command, Consumer<String[]> handler) {
        commandHandlers.put(command, handler);
    }

    public void processMessage(String message) {
        String[] parts = message.split(delimiter);
        if (parts.length > 0) {
            String command = parts[0];
            String[] arguments = new String[parts.length - 1];
            System.arraycopy(parts, 1, arguments, 0, arguments.length);

            Consumer<String[]> handler = commandHandlers.get(command);
            if (handler != null) {
                handler.accept(arguments);
            } else {
                System.out.println("未找到命令处理器: " + command);
            }
        }
    }

    public String buildMessage(String command, String... arguments) {
        StringBuilder sb = new StringBuilder(command);
        for (String arg : arguments) {
            sb.append(delimiter).append(arg);
        }
        return sb.toString();
    }

    // 示例用法
    public static void main(String[] args) {
        CmdMessenger messenger = new CmdMessenger(";");

        // 注册命令处理器
        messenger.registerHandler("LOGIN", argsArray -> {
            System.out.println("登录用户: " + argsArray[0]);
            System.out.println("密码: " + argsArray[1]);
        });

        messenger.registerHandler("MESSAGE", argsArray -> {
            System.out.println("收到消息: " + String.join(" ", argsArray));
        });

        // 处理消息
        messenger.processMessage("LOGIN;user123;pass456");
        messenger.processMessage("MESSAGE;Hello;World!");
        messenger.processMessage("UNKNOWN;arg1;arg2");

        // 构建消息
//        String message = messenger.buildMessage("LOGOUT", "user123");
//        System.out.println("构建的消息: " + message);
    }
}
